package com.guagua.chat.base;
/**
 * 北京八度互联科技有限公司版权所有
 * Copyright (C) Badu Corporation. All Rights Reserved
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.NamingException;

import com.guagua.base.database.ConnectionManager;
import com.guagua.chat.room.ChatRoomUtil;



/** ******************************************************************
* 类概要:数据库操作基类
* @author 郑国英
* @version 2012-3-20 下午8:00:00
*******************************************************************/
public class BaseDao {
	public static final String JNDI_NAME = "guagua/homepage";    //数据源名称
	public static final String POOL_SNS = "proxool.sns";    //数据源名称
	public static final String CHATROOM_JNDI_NAME = "guagua/chatroom";//主站
	/**
	 * 函数说明：根据sql语句获取分页对象，包括总页数、总记录数，当前页面，每页记录数 <br/>
	 * 
     * @param sql
	 *            类型:(String)；<br/> 需要分页的sql语句<br/>；
	 * @param currentPage
	 *            类型:(int)；<br/> 当前查询的页码<br/>；
	 * @param pageSize
	 *            类型:(int)；<br/> 每页记录数<br/>；
	 * @return 返回结果说明. （PaginationInfo）分页对象
	 */
	public  PaginationInfo getPagination(String sql, int curpage, int pagesize) {
		String sql_ = "select count(1) from ("+sql+") temp_";
		int count_ = 0;
		PaginationInfo paginationInfo_ = null;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			con = ConnectionManager.getDataSourceConnection(JNDI_NAME);
			pstmt = con.prepareStatement(sql_);
			rs = pstmt.executeQuery();
			if(rs.next()){
				count_ = rs.getInt(1);
			}
			//这里为了防止报错
			int tolPage = ChatRoomUtil.getMaxPage(pagesize,count_);
			if(curpage>tolPage){curpage=tolPage;}
			//
			paginationInfo_ = new PaginationInfo(curpage, pagesize, count_);
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			ConnectionManager.closeConnection(rs, pstmt, con);
		}
		return paginationInfo_;
	}
	/**
	 * 函数说明：将分页对象转化为json串格式 <br/>
	 * 
     * @param page
	 *            类型:(PaginationInfo)；<br/> 分页对象<br/>；
	 * @return 返回结果说明. （String）json串
	 */
	public  String getPagingJsonStr(PaginationInfo page){
		StringBuffer sb = new StringBuffer(100);
		sb.append("[{\"curPage\":\""+page.getIntPage());
		sb.append("\",\"totalPages\":\""+page.getIntPageCount());
		sb.append("\",\"totalRecords\":\""+page.getIntRowCount());
		sb.append("\",\"isHasPrevious\":\""+page.isHasPrevious());
		sb.append("\",\"isHasNext\":\""+page.isHasNext());
		sb.append("\",\"pageSize\":\""+page.getIntPageSize()+"\"}]");
		return sb.toString();
	}
	
	/**
	 * 函数说明：将分页对象转化为json串格式 <br/>
	 * 
     * @param page
	 *            类型:(PaginationInfo)；<br/> 分页对象<br/>；
	 * @return 返回结果说明. （String）json串
	 */
	public  String getPagingJsonStr1(PaginationInfo page){
		StringBuffer sb = new StringBuffer(100);
		sb.append("[{curPage:"+page.getIntPage());
		sb.append(",totalPages:"+page.getIntPageCount());
		sb.append(",totalRecords:"+page.getIntRowCount());
		sb.append(",isHasPrevious:"+page.isHasPrevious());
		sb.append(",isHasNext:"+page.isHasNext());
		sb.append(",pageSize:"+page.getIntPageSize()+"}]");
		return sb.toString();
	}
	
	 /**

     * 功能：根据分页条件组成可以实现分页的sql语句，只针对sqlserver数据库

     * <br/>

     * @param pi 类型:(PaginationInfo)；  分页对象，包含当前页，每页记录数，总记录数<br/> 
     * @param sql_condition 类型:(String)；  需要实现分页的sql语句<br/> 

     * @return 执行结果实现分页的sql语句，主要是通过ROW_NUMBER()函数实现

     */
    public String genPagingSql(PaginationInfo pi,String ...sql_condition){
    	int cur_page=pi.getIntPage();
    	int page_size=pi.getIntPageSize();
		int nStartRow = (cur_page - 1) * page_size + 1;
		int nEndRow   =  cur_page * page_size;
		//去掉select
		String sql_temp = sql_condition[0].trim();
		StringBuffer sql_ = new StringBuffer("SELECT * FROM (SELECT TOP 100 PERCENT ROW_NUMBER() OVER(order by ");
		sql_.append(sql_condition[1]).append(") AS rowNum, ");
		sql_.append(sql_temp.substring(6));
		
		sql_.append(" ) AS myTable WHERE rowNum BETWEEN ");
		sql_.append(nStartRow).append(" AND ").append(nEndRow);
		
		return sql_.toString();
	}
	

}
